<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Import extends Controller
{
	public function action_index()
	{
		if(!$this->is_cli())
		{
			die("This script can only be run from the CLI");
		}
		
		$xml = simplexml_load_file(DOCROOT."../musicnet_data.xml");
		$count = 0;
		
		Database::instance()->query(Database::UPDATE, "SET NAMES 'utf8'", false);
		
		Database::instance()->query(Database::UPDATE, "TRUNCATE people", false);
		Database::instance()->query(Database::UPDATE, "TRUNCATE variants", false);
		
		foreach($xml as $person_xml)
		{
			$person_orm = ORM::factory('person');
			$person_orm->name = $person_xml->label;
			$person_orm->musicnetid = $person_xml->attributes()->musicnetid;
			$person_orm->birth_date = $person_xml->birthdate;
			$person_orm->death_date = $person_xml->deathdate;
			$person_orm->a2z = strtolower(substr(iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $person_xml->label), 0,1));
			$person_orm->save();

			$variants = 0;

			// Create All the variants
			foreach($person_xml->namevariants->variant as $variant_xml)
			{
				$variant_orm = ORM::factory('variant');
				$variant_orm->name = $variant_xml."";
				$variant_orm->catalog = $variant_xml->attributes()->catalog;
				$variant_orm->link = $variant_xml->attributes()->url;
				
				$variant_orm->person_id = $person_orm->id;
				$variant_orm->save();
				
				$variants++;
			}
			
			echo "Imported: '{$person_orm->name}' with $variants variants\n";
			$count++;
		}
		
		echo "Imported $count people\n";
	}
	
	private function is_cli()
	{
		return (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']));
	}
}